package com.weixing.mall.provider.controller.admin;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.SysAuth;
import com.weixing.mall.core.support.auth.SysInfo;
import com.weixing.mall.provider.api.model.vo.ProductStockVo;
import com.weixing.mall.provider.model.domain.Depot;
import com.weixing.mall.provider.model.domain.ProductStock;
import com.weixing.mall.provider.model.domain.ProductStockDetails;
import com.weixing.mall.provider.model.dto.ProductStockDto;
import com.weixing.mall.provider.model.dto.ProductStockSaveDto;
import com.weixing.mall.provider.model.enums.DepotTypeEunm;
import com.weixing.mall.provider.model.enums.SysDepotTypeEunm;
import com.weixing.mall.provider.model.query.ProductStockQuery;
import com.weixing.mall.provider.model.vo.ProductStockListVo;
import com.weixing.mall.provider.service.IDepotExtraService;
import com.weixing.mall.provider.service.IProductStockDetailsService;
import com.weixing.mall.provider.service.IProductStockService;
import com.weixing.mall.provider.support.excaldata.ProductStockDetailsListED;
import com.weixing.mall.provider.support.excaldata.ProductStockED;
import com.weixing.mall.provider.support.excaldata.ProductStockListED;
import com.weixing.mall.provider.support.excaldata.StockCodeData;
import com.weixing.mall.provider.support.excalservice.DepotExcalService;
import com.weixing.mall.provider.support.excalservice.ProductStockDataListener;
import com.weixing.mall.provider.support.excalservice.ProductStockDetailsDataListener;
import com.weixing.mall.provider.support.excalservice.StockCodeDataListener;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ProductStockController
 * @Description TODO <br/>
 * @Author gjq
 * @Modified By:
 * @Date 2019/10/25
 * @Version 1.0
 **/
@RequestMapping("productStock")
@RestController
@Api(value = "库存管理Api", tags = "库存管理")
public class ProductStockController extends BaseController {

    @Autowired
    private IProductStockService productStockService;
    @Autowired
    private IDepotExtraService depotExtraService;
    @Autowired
    private IProductStockDetailsService productStockDetailsService;

    /**
     * 二期项目已经找到替代办法，
     *
     * @param productStockQuery
     * @return
     */
    @ApiOperation(value = "库存管理列表")
    @GetMapping("")
    @Deprecated
    public Result selectOfPage(ProductStockQuery productStockQuery) {
        Map<String, Object> map = new HashMap<>();
        Map returnMap = productStockService.totalQuantityAndAmount(productStockQuery);
        if (returnMap == null) {
            returnMap = new HashMap<String, Object>();
            returnMap.put("totalQuantity", 0);
            returnMap.put("totalAmount", 0);
        }
        map.putAll(returnMap);
        map.put("data", productStockService.selectOfPage(initMpPage(), productStockQuery));
        return ResultUtil.success(map);
    }

    /**
     * 库存管理二期列表
     *
     * @param productStockQuery 查询条件
     * @return
     */
    @ApiOperation(value = "库存管理二期列表")
    @GetMapping("/newList")
    @NoNeedAccess
    public Result selectOfNewPage(ProductStockQuery productStockQuery) {
        Map<String, Object> map = new HashMap<>();
        Map returnMap = productStockDetailsService.totalQuantityAndAmount(productStockQuery);
        if (returnMap == null) {
            returnMap = new HashMap<String, Object>();
            returnMap.put("totalQuantity", 0);
            returnMap.put("totalAmount", 0);
        }
        map.putAll(returnMap);
        map.put("data", productStockDetailsService.selectOfPage(initMpPage(), productStockQuery));
        return ResultUtil.success(map);
    }

    /**
     * 二期项目库存列表的导出
     *
     * @param productStockQuery
     * @param response
     */
    @ApiOperation(value = "库存管理列表导出Excel")
    @GetMapping("exportExcelLeve2")
    @NoNeedAccess
    public void downLongLeve2(ProductStockQuery productStockQuery, HttpServletResponse response) {
        IPage<ProductStockListVo> list = productStockDetailsService.selectOfPage(initMpPage().setSize(-1), productStockQuery);
        try {
            String fileName = "库存管理列表";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            if (StrUtil.isEmpty(fileName)) {
                fileName = DateUtil.now();
            }
            String fileName2 = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName2 + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ProductStockListED.class).sheet(fileName).doWrite(DepotExcalService.loadProductStockListList(list.getRecords()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "库存管理列表导出Excel")
    @GetMapping("exportExcel")
    public void downLong(ProductStockQuery productStockQuery, HttpServletResponse response) {
        IPage<ProductStockListVo> list = productStockService.selectOfPage(initMpPage().setSize(-1), productStockQuery);
        try {
            String fileName = "库存管理列表";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            if (StrUtil.isEmpty(fileName)) {
                fileName = DateUtil.now();
            }
            String fileName2 = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName2 + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ProductStockListED.class).sheet(fileName).doWrite(DepotExcalService.loadProductStockListList(list.getRecords()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 二期不在需要库位的单独查询
     *
     * @param depotId
     * @param productIdArray
     * @return
     */
    @ApiOperation(value = "库位查询")
    @GetMapping("/getStoreHouse")
    @Deprecated
    public Result getStoreHouse(Long depotId, String productIdArray) {
        String[] productIds = productIdArray.split(",");
        List<ProductStock> stockLists = productStockService.list(new QueryWrapper<ProductStock>().eq("depot_id", depotId).in("product_id", productIds));
        return ResultUtil.success(stockLists);
    }

    /**
     * 二期查询库存的内容
     *
     * @param productStockQuery
     * @return
     */
    @ApiOperation(value = "查询库存内容")
    @GetMapping("/selectListLevel2")
    public Result selectListLevel2(ProductStockQuery productStockQuery) {
        return ResultUtil.success(productStockDetailsService.selectList(productStockQuery));
    }

    @ApiOperation(value = "查询库存内容")
    @GetMapping("/selectList")
    public Result selectList(ProductStockQuery productStockQuery) {
        return ResultUtil.success(productStockService.selectList(productStockQuery));
    }

    @ApiOperation(value = "保存库存 (1调货/2入库/3出库)")
    @PostMapping("save")
    @NoRepeatSubmit
    public Result save(@SysInfo SysAuth auth, ProductStockSaveDto productStockSaveDto) {
        productStockService.saveList(productStockSaveDto, auth.getUid());
        return ResultUtil.success();
    }

//    @ApiOperation(value = "商品首次入库（暂时不用）")
//    @PostMapping("saveinit")
//    @NoRepeatSubmit
//    public Result saveinit(@SysInfo SysAuth auth, List<ProductStockDto> ProductStockDto) {
//        productStockService.saveInitList(ProductStockDto, auth.getUid());
//        return ResultUtil.success();
//    }

    @ApiOperation(value = "出库类型")
    @GetMapping("depotType")
    public Result depotType() {
        return ResultUtil.success(SysDepotTypeEunm.values());
    }

    @ApiOperation(value = "啦啦啦啦啦啦啦啦啦啦啦啦啦")
    @GetMapping("inOutStock")
    public Result inOutStock(Long depotId, Long productId, Integer flag, Long uid) {
        productStockService.inOutStock(depotId, productId, flag, uid, null);
        return ResultUtil.success();
    }

    @ApiOperation("出库单批量导入数据处理")
    @PostMapping(value = "importExcal/{depotId}")
    public Result productStockImportData(@PathVariable(value = "depotId") Long depotId, MultipartFile file) {
        ProductStockDataListener psdl = new ProductStockDataListener(depotId, productStockService);
        try {
            EasyExcel.read(file.getInputStream(), ProductStockED.class, psdl).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error("failed");
        }
        return ResultUtil.success(psdl.getReturnList());
    }

    @ApiOperation("库位和仓库编码初始化")
    @PostMapping(value = "initStockCode/{depotId}")
    public Result initStockCode(@PathVariable(value = "depotId") Long depotId, MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), StockCodeData.class, new StockCodeDataListener(depotId, productStockDetailsService, depotExtraService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error("Excel导入失败");
        }
        return ResultUtil.success();
    }

    @ApiOperation(value = "库存管理二期列表")
    @GetMapping("/testList")
    public Result testList(ProductStockQuery productStockQuery) {
        List<ProductStock> productStocks = productStockService.list();
        for (ProductStock productStock : productStocks) {
            ProductStockDetails productStockDetails = new ProductStockDetails();
            BeanUtils.copyProperties(productStock, productStockDetails);
            productStockDetailsService.save(productStockDetails);
        }
        /*Map<String,Object> map = new HashMap<>();
        Map returnMap = productStockDetailsService.totalQuantityAndAmount(productStockQuery);
        if(returnMap == null){
            returnMap = new HashMap<String,Object>();
            returnMap.put("totalQuantity",0);
            returnMap.put("totalAmount",0);
        }
        map.putAll(returnMap);
        map.put("data",productStockDetailsService.selectOfPage(initMpPage(), productStockQuery));*/
        return ResultUtil.success();
    }

    @ApiOperation("仓库数据初始化操作")
    @PostMapping(value = "testinitDepot")
    @NoNeedAccess
    public Result testinitDepot(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), ProductStockDetailsListED.class, new ProductStockDetailsDataListener(productStockDetailsService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error("Excel导入失败");
        }
        return ResultUtil.success();
    }
}
